<template>

  <!-- <div> -->
    <div class="content-wrapper-store">
      <loginOut :pageName="t('materialStore.pageTitle')" />
      <div class="content">
        <!-- 序列号输入区域 -->
        <div class="serial-input-wrapper">
          <div class="serial-input-container">
            <!-- <div style="width: 70px">{{ t('materialStore.scanLabel') }}</div> -->
            <el-input
              v-model="serial"
              class="serial-input"
              :placeholder="t('materialStore.inputPlaceholder')"
              clearable
              @keyup.enter="handleSerialInput"
              ref="inputRef"
            >
              <template #prefix>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-input>
          </div>
          <el-button type="primary" @click="openAddDialog"> {{ t('materialStore.buttons.add') }} </el-button>
        </div>

        <!-- 序列号信息列表 -->
        <div class="serial-list-container">
          <!-- <div class="t">{{ t('materialStore.inboundListTitle') }}</div> -->
          <el-table
            v-loading="loading"
            :data="list"
            border
            :height="500"
            style="width: 100%"
            :empty-text="t('materialStore.emptyText')"
          >
            <el-table-column prop="serialNo" :label="t('materialStore.table.serialNo')" align="center" min-width="180" />
            <el-table-column prop="itemCode" :label="t('materialStore.table.itemCode')" align="center" min-width="120" />
            <el-table-column prop="diskNo" :label="t('materialStore.table.diskNo')" align="center" min-width="100" />
            <el-table-column prop="qty" :label="t('materialStore.table.qty')" align="center" min-width="120" />
            <el-table-column prop="location" :label="t('materialStore.table.location')"  align="center" min-width="120" />
            <el-table-column
              prop="receiveDate"
              :label="t('materialStore.table.receiveDate')"
              align="center"
              min-width="140"
              :formatter="formatDate"
            />
            <el-table-column prop="receiver" :label="t('materialStore.table.receiver')" align="center" min-width="100" />
            <el-table-column :label="t('table.action')" align="center" >
              <template #default="scope">
                <!-- 只有通过对话框添加的记录才显示打印条码按钮 -->
                <el-button
                  v-if="!scope.row.isScanned"
                  size="small"
                  type="text"
                  @click="printCode(scope.row)"
                  danger
                >
                  {{ t('materialStore.buttons.printBarcode') }}
                </el-button>
                <el-button size="small" type="text" @click="handleDelete(scope.row)" danger>
                  {{ t('materialStore.buttons.delete') }}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 添加记录对话框 -->
        <el-dialog
          v-model="addDialogVisible"
          :title="t('materialStore.dialog.addTitle')"
          width="40%"
          :close-on-click-modal="false"

        >
          <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="140px">
            <el-form-item :label="t('materialStore.dialog.itemCodeLabel')"  prop="itemCode">
              <el-input v-model="addForm.itemCode" clearable />
            </el-form-item>
            <el-form-item :label="t('materialStore.dialog.quantityLabel')"  prop="quantity">
              <el-input v-model.number="addForm.quantity" type="number" clearable />
            </el-form-item>
            <el-form-item :label="t('materialStore.dialog.unitLabel')" prop="unit">
              <el-input v-model="addForm.unit" clearable />
            </el-form-item>
            <el-form-item :label="t('materialStore.dialog.locationLabel')"  prop="location">
              <el-input v-model="addForm.location" clearable />
            </el-form-item>
          </el-form>
          <template #footer>
            <el-button @click="addDialogVisible = false">{{ t('materialStore.buttons.cancel') }}</el-button>
            <el-button type="primary" @click="handleAddRecord">{{ t('materialStore.buttons.confirm') }}</el-button>
          </template>
        </el-dialog>
      </div>
    </div>
    <!-- 调用打印组件 -->
    <PrintQrCode
      :visible="printDialogVisible"
      :currentMaterialsItem="selectedMaterialsItem"
      @reset="resetState"
    />
    <!-- 底部按钮区域 -->
    <div class="button-container-b">
      <div class="right-buttons">
        <el-button type="success" @click="saveData"> {{ t('materialStore.buttons.save') }} </el-button>
        <el-button @click="cancelOperation"> {{ t('materialStore.buttons.cancel') }}  </el-button>
      </div>
    </div>
  <!-- </div> -->
</template>

<script setup lang="ts">
import { Search } from '@element-plus/icons-vue'
import { onMounted, ref, reactive, nextTick, defineOptions } from 'vue'
import PrintQrCode from '@/views/customer/material/components/PrintQrCode.vue'
import { MaterialInventorApi } from '@/api/opticore/materialinventor'
import loginOut from '@/components/loginOut/index.vue'

/** 物料入库 列表 */
defineOptions({ name: 'MaterialStore' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

// 状态管理
const loading = ref(false) // 列表的加载中
const list = ref<any[]>([]) // 列表的数据
const serial = ref('') // 物料序列号
const inputRef = ref() // 输入框引用
const addDialogVisible = ref(false) // 添加对话框显示状态

// 添加表单
const addForm = ref({
  itemCode: '',
  quantity: '',
  unit: '',
  location: ''
})

// 添加表单验证规则
const addFormRules = reactive({
  itemCode: [{ required: true, message: t('materialStore.rules.itemCodeRequired'), trigger: 'blur' }],
  quantity: [
    { required: true, message: t('materialStore.rules.quantityRequired'), trigger: 'blur' },
    { type: 'number', message: t('materialStore.rules.quantityMustBeNumber'), trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value < 0) {
          callback(new Error(t('materialStore.rules.quantityCannotBeNegative')))
        } else {
          callback() // 校验通过
        }
      },
      trigger: 'blur'
    }
  ],
  unit: [{ required: true, message:  t('materialStore.rules.unitRequired'), trigger: 'blur' }]
})

const addFormRef = ref() // 添加表单引用

// 报工表单
const form = ref({
  serialId: '',
  workOrder: '', // 工单号
  quantity: '',
  operator: JSON.parse(localStorage.getItem('userInfo') || '{}').nickname || '' // 默认值
})

/** 处理序列号输入（扫描添加） */
const handleSerialInput = () => {
  const inputValue = serial.value.trim()
  if (!inputValue) {
    message.warning(t('materialStore.messages.enterSerial'))
    return
  }

  // 检查序列号唯一性
  if (list.value.some((item) => item.serialNo === inputValue)) {
    message.warning(t('materialStore.messages.serialExists'))
    return
  }

  // 解析序列号: 112-001-204/100M/250709/00001
  let itemCodeSplit = ''
  let qtySplit = ''
  let batchNOSplit = null

  let parts = inputValue.split('/')
  if (parts.length < 2) {
    parts =inputValue.split(',')
    if(parts.length < 3){
      message.warning(t('materialStore.messages.invalidSerialFormat'))
      return
    }

    qtySplit = parts[parts.length - 2]
    itemCodeSplit = parts[parts.length - 3]
    batchNOSplit =  parts[parts.length - 1]
    
  } else {
    qtySplit = parts[1]
    itemCodeSplit = parts[0]
    batchNOSplit =  null
  }

  // 构建新记录，添加isScanned标记为true（表示是扫描添加）
  let newRecord = {
    id: Date.now(), // 生成唯一ID
    serialNo: inputValue, // 完整序列号
    itemCode: itemCodeSplit, // 品号: 112-001-204
    qty: qtySplit, // 数量和单位: 100M
    batchNo: batchNOSplit,
    // diskNo: parts.length > 2 ? parts[2] : '', // 纤盘号: 250709
    // location: parts.length > 3 ? parts[3] : '', // 入库位置
    receiveDate: new Date().toISOString(), // 当前时间
    receiver: form.value.operator, // 入库人
    isScanned: true // 标记为扫描添加的记录
  }

  // 添加到列表
  list.value = [...list.value, newRecord]

  // 清空输入框
  serial.value = ''

  // 聚焦输入框
  nextTick(() => {
    inputRef.value?.focus()
  })

  message.success(t('materialStore.messages.addSuccess'))
}

/** 打开添加对话框 */
const openAddDialog = () => {
  // 重置表单
  addForm.value = {
    itemCode: '',
    quantity: '',
    unit: '',
    location: ''
  }
  // 显示对话框
  addDialogVisible.value = true
}

/** 处理添加记录（对话框添加） */
const handleAddRecord = () => {
  // 表单验证
  addFormRef.value?.validate((valid: boolean) => {
    if (!valid) return false

    // 生成序列号
    const now = new Date()
    const year = now.getFullYear().toString().slice(2) // 年后两位
    const month = (now.getMonth() + 1).toString().padStart(2, '0') // 月两位
    const day = now.getDate().toString().padStart(2, '0') // 日两位

    // 获取当前相同品号的记录数量
    const sameProductRecords = list.value.filter(
      (item) => item.itemCode === addForm.value.itemCode
    ).length

    // 生成流水号，格式为5位数字，不足补零
    const serialNumber = (sameProductRecords + 1).toString().padStart(5, '0')

    // 构建完整序列号: 品号/数量单位/年后两位月两位日两位/流水号
    let serialNo = `${addForm.value.itemCode}/${addForm.value.quantity}${addForm.value.unit}/${year}${month}${day}/${serialNumber}`

    // 检查序列号唯一性
    if (list.value.some((item) => item.serialNo === serialNo)) {
      message.warning(t('materialStore.messages.serialGeneratedExists'))
      return
    }

    try {
      // 调用校验接口将返回值复制给serialNo
      MaterialInventorApi.checkMaterialInventor(serialNo).then((res) => {
        serialNo = res
        // 构建新记录，添加isScanned标记为false（表示是手动添加）
        const newRecord = {
          id: Date.now(),
          serialNo,
          itemCode: addForm.value.itemCode,
          qty: `${addForm.value.quantity}${addForm.value.unit}`,
          location: addForm.value.location,
          receiveDate: new Date().toISOString(),
          receiver: form.value.operator,
          isScanned: false // 标记为手动添加的记录
        }

        // 添加到列表
        list.value = [...list.value, newRecord]

        // 关闭对话框
        addDialogVisible.value = false

        message.success(t('materialStore.messages.addSuccess'))
      })
    } catch (e) {
      message.warning(t('materialStore.messages.serialGeneratedExists'))
      return
    }
  })
}

/** 添加空行 */
const addEmptyRow = () => {
  const newRecord = {
    id: Date.now(),
    serialNo: '',
    itemCode: '',
    qty: '',
    diskNo: '',
    location: '',
    receiveDate: new Date().toISOString(),
    receiver: form.value.operator, // 入库人
    isScanned: false // 空行默认按手动添加处理
  }

  list.value = [...list.value, newRecord]
  message.info('已添加空行，请编辑')
}

/** 保存数据 */
const saveData = async () => {
  if (list.value.length === 0) {
    message.warning(t('materialStore.messages.listEmpty'))
    return
  }

  try {
    loading.value = true

    // 准备入库数据
    const storeData = list.value.map((item) => ({
      ...item,
      qty: Number(item.qty.replace(/[^0-9.]/g, '')), // 确保数量为数字
      unit: item.qty.replace(/[0-9.]/g, '') // 提取单位部分
    }))

    // 调用入库接口
    await MaterialInventorApi.storeMaterialInventor(storeData)

    // 保存成功后清空列表
    list.value = []
    message.success(t('materialStore.messages.saveSuccess'))
  } catch (error) {
    console.error('保存入库数据失败:', error)
  } finally {
    loading.value = false
  }
}

/** 取消操作 */
const cancelOperation = () => {
  // 询问用户是否确认取消
  ElMessageBox.confirm(t('materialStore.messages.cancelConfirm'),
    t('materialStore.messages.prompt'), {
    confirmButtonText: t('materialStore.buttons.confirm'),
      cancelButtonText: t('materialStore.buttons.cancel'),
    type: 'warning'
  })
    .then(() => {
      // 清空列表
      list.value = []
      message.info(t('materialStore.messages.listCleared'))
    })
    .catch(() => {
      // 用户取消了操作
      message.info(t('materialStore.messages.operationCancelled'))
    })
}

/** 格式化入库日期显示 */
const formatDate = (row: any, column: any) => {
  if (!row.receiveDate) return '-'
  return new Date(row.receiveDate).toLocaleString()
}

/** 处理删除操作 */
const handleDelete = (row: any) => {
  // 过滤掉要删除的记录
  list.value = list.value.filter((item) => item.id !== row.id)
  message.success(t('materialStore.messages.deleteSuccess'))
}

const printDialogVisible = ref(false)
const selectedMaterialsItem = ref<any>({})
/** 打印方法 */
const printCode = (item: any) => {
  console.log(item)
  selectedMaterialsItem.value = item
  printDialogVisible.value = true
}

function resetState() {
  printDialogVisible.value = false
  console.log(printDialogVisible.value)
}

/** 初始化 **/
onMounted(() => {
  // 聚焦输入框
  nextTick(() => {
    inputRef.value?.focus()
  })
})
</script>

<style scoped lang="less">
.content-wrapper-store {
  height: 100vh;
    padding: 0 16px;
    margin-top: 70px;
    background-color: #e7edf6;
}
.content {
  width: 100%;
  /* height: 600px; */
  /* background-color: #fff; */
}
.work-report-container {
  padding: 40px 20px;
  min-height: 100vh;
}

.serial-input-wrapper {
  margin-bottom: 16px;

  padding: 20px;
  background-color: #fff;
  display: flex;
  justify-content: space-between;
  /* margin: 40px 0; */
}

.serial-input-container {
  display: flex;
  align-items: center;
  width: 50%;
  max-width: 600px;
}

.serial-input {
  width: 100%;
  height: 44px;
  font-size: 16px;
}

.serial-list-container {
  padding: 16px;
  margin-top: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 4px;
  background-color: #fff;
  /* overflow: hidden; */
  .t {
    margin-bottom: 16px;
    font-size: 16px;
    color: #515a6e;
    font-weight: 600;
  }
}

.button-container-b {
  position: fixed;
  bottom: 0;
  right: 0;
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
  padding: 16px 10px;
  width: 100vw;
  z-index: 999;
  background-color: #fff;
}

.right-buttons {
  display: flex;
  gap: 10px;
}

::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: bold;
}

::v-deep .el-table tr:hover > td {
  background-color: #f9fafb !important;
}

::v-deep .el-table--border th,
::v-deep .el-table--border td {
  border-right: 1px solid #e5e7eb;
}

::v-deep .el-table--border {
  border-left: 1px solid #e5e7eb;
}
</style>
